/*
 * KeyRef.java
 *
 * Created on 20 marzo 2004, 10.43
 */

package net.ermannofranco.xml.schema;

import net.ermannofranco.xml.Static;
import net.ermannofranco.xml.Tag;

/**
 * 
 * @author ermanno (ermanno.franco@gmail.com)
 */
public class Keyref extends SchemaTag {

	private static final long serialVersionUID = -8321151881581479568L;
	private int counter;
	private boolean selector;
	private boolean named;
	private boolean referred;

	/**
	 * Creates a new instance of Keyref Protetto
	 * 
	 * @param level
	 *            livello di indentazione
	 * @param container
	 *            tag contenitore
	 */
	protected Keyref(int level, ISchemaTag container) {
		super("keyref", level, container);
	}

	/**
	 * @param name
	 * @return
	 */
	public Keyref setName(String name) {
		Static.validateNMToken(name);

		addAttr("name", name);
		named = true;
		return this;
	}

	/**
	 * @param name
	 * @return
	 */
	public Keyref setRefer(String name) {
		Static.validateNMToken(name);

		addAttr("refer", name);
		referred = true;
		return this;
	}

	/**
	 * @return
	 */
	public Selector setSelector() {
		Selector se;
		add(se = new Selector(getLevel() + 1, this));
		selector = true;
		return se;
	}

	/**
	 * @return
	 */
	public Field addField() {
		Field se;
		add(se = new Field(getLevel() + 1, this));
		counter++;
		return se;
	}

	/**
	 * aggiunge un tag Annotation che contiene un tag Documentation
	 * 
	 * @param explanation
	 *            Stringa di documentazione
	 * @return autoriferimento all'oggetto corrente
	 */
	public Keyref addDocumentation(String explanation) {
		addAnnotation().addDocumentation(explanation);
		return this;
	}

	/**
	 * aggiunge un tag Annotation che contiene un tag Documentation
	 * 
	 * @param explanation
	 *            testo della documentazione
	 * @param language
	 *            attributo di xml:lang, seguire le regole di i18n
	 * @return riferimento all'oggetto corrente
	 */
	public Keyref addDocumentation(String explanation, String language) {
		addAnnotation().addDocumentation(explanation, language);
		return this;
	}

	private void validateUnique() {
		if (!named)
			throw new SchemaException("name e' obbligatorio, "
					+ getClass().getName() + ":(" + getName() + ")");
		if (!referred)
			throw new SchemaException("refer e' obbligatorio, "
					+ getClass().getName() + ":(" + getName() + ")");
		if (!selector)
			throw new SchemaException("Un Selector e' obbligatorio, "
					+ getClass().getName() + ":(" + getName() + ")");
		if (counter == 0)
			throw new SchemaException("Almeno un Field e' richiesto, "
					+ getClass().getName() + ":(" + getName() + ")");
	}

	/**
	 * semplice override di convalida
	 * 
	 * @return 
	 */
	public String toPrint() {
		validateUnique();
		return super.toPrint();
	}
	public String toSave() {
		validateUnique();
		return super.toSave();
	}
}
